package com.koron.common.web.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.koron.common.bean.PubDepartmentBean;
import com.koron.common.bean.StaffBean;
import com.koron.common.bean.query.StaffQueryBean;
import com.koron.common.web.mapper.PubDepartmentNewMapper;
import com.koron.css2.common.bean.MessageEntity;
import com.koron.util.JsonUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.koron.ebs.mybatis.TaskAnnotation;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class DepartmentService {

    @TaskAnnotation("list")
    public String list(SessionFactory factory,String id,String type){
        PubDepartmentNewMapper mapper = factory.getMapper(PubDepartmentNewMapper.class);
        List<PubDepartmentBean> list = mapper.list(id,"one");
        if (!"all".equals(type)){
            return JsonUtils.objectToJson(list);
        }
        return JsonUtils.objectToJson(fun(mapper,list));
    }

    private List<PubDepartmentBean> fun(PubDepartmentNewMapper mapper, List<PubDepartmentBean> list){
        if (list == null || list.isEmpty()){
            return null;
        }
        for (PubDepartmentBean item : list){
            List<PubDepartmentBean> list1 = mapper.list(item.getId(),"other");
            item.setChildren(list1);
            fun(mapper, list1);
        }
        return list;
    }

    @TaskAnnotation("listStaff")
    public String listStaff(SessionFactory factory,String departmentCode,String name){
        PubDepartmentNewMapper mapper = factory.getMapper(PubDepartmentNewMapper.class);
        List<Map> list = mapper.listStaff(departmentCode,name);
        return JsonUtils.objectToJson(list);
    }

    @TaskAnnotation("query")
    public String query(SessionFactory factory,StaffQueryBean query){
        PubDepartmentNewMapper mapper = factory.getMapper(PubDepartmentNewMapper.class);
        Page<?> page = PageHelper.startPage(query.getPage(), query.getPageCount());
        List<StaffBean> staff = mapper.selectList(query);
        return MessageEntity.success(staff, page.getPageNum(), page.getTotal(), "查询成功").toJson();
    }

}
